package com.lcgserver;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 作者: LCG
 * 日期: 2020/8/4 17:15
 * 描述:
 */
public class TestServer {

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, KeeperException, InterruptedException {


        ServerSocket serverSocket=new ServerSocket();

        serverSocket.bind(new InetSocketAddress("localhost",10000));

        //注册服务
        init();

        while (true){
            //监听访问
            Socket accept = serverSocket.accept();

            ObjectInputStream ois=new ObjectInputStream(accept.getInputStream());

            //传递的参数
            Object[] pargs=(Object[]) ois.readObject();
            //实现类的名称
            String className=(String)ois.readUTF();
            //方法的名称
            String methodName=(String)ois.readUTF();
            //参数类型
            Class<?> [] paramterTypes=(Class<?> [])ois.readObject();


            //实现类的实体
            Class<?> service=Class.forName(className);

            //获得执行的方法
            Method method=service.getMethod(methodName, paramterTypes);

            //获取要执行的Service的对象
            Object serviceObject = service.newInstance();
            //通过反射执行方法
            Object invoke = method.invoke(serviceObject, pargs);

            //回写方法执行的结果
            OutputStream outputStream = accept.getOutputStream();

            ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);

            //返回给客户端结果
            objectOutputStream.writeObject(invoke);

        }


    }

    /**
     * 初始化注册服务
     */
    public static void init() throws IOException, KeeperException, InterruptedException {

        ZooKeeper zooKeeper=new ZooKeeper("localhost",2181,new TestWatcher());

        //注册服务信息
        String service="com.lcgserver.service.TestServiceImpl";
        zooKeeper.create("/mydubbo",service.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

        zooKeeper.create("/mydubbo/com.lcg.TestService",service.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);



    }

}
